<template>
    <div>
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
            <el-form-item label="旧密码" prop="oldpass">
                <el-input v-model="ruleForm.oldpass" type="password" autocomplete="off" show-password/>
            </el-form-item>
            <el-form-item label="新密码" prop="newPass">
                <el-input v-model="ruleForm.newPass" type="password" autocomplete="off" show-password @keyup.enter="submitForm"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { changeAdminPsd } from "@/api/admin";
import { ElMessage } from 'element-plus';
import { useRouter } from "vue-router";
// 路由
const router = useRouter();
const ruleFormRef = ref<InstanceType<typeof FormInstance>>()
const ruleForm = reactive({
    oldpass: '',
    newPass: '',
})
// 自定义密码校验
const validatePass = (rule: any, value: any, callback: any) => {
if (!/^\w{3,}$/.test(value)) {
        callback(new Error("密码最少3位"));
    } else {
        callback();
    }
}
const rules = reactive<InstanceType<typeof FormRules>>({
    password: [{ required: true, validator: validatePass, trigger: 'blur' }],
})
function submitForm(){
 //   保证表单验证通过
 ruleFormRef.value.validate((valid: Boolean) => {
    if(valid){
        // 调用axios
        changeAdminPsd({
            oldPassword:ruleForm.oldpass,
            password:ruleForm.newPass,
            id:localStorage.getItem("id")
        }).then(resp=>{
            if (resp.data.code == 20000){
                 // 提示修改密码成功
                 ElMessage({
                        message: '修改密码成功!',
                        type: 'success',
                    })

            }else if(resp.data.code == 50000){
                    ElMessage.error(resp.data.msg)
                }
        })
    }
})
}
</script>

<style scoped></style>